﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Serialization;
using NonLeagueExplorer.Config;

namespace NonLeagueExplorer.Forms
{
    public partial class OptionsForm : Form
    {
        private ConfigData ConfigOptions;
        private bool ConfigLoaded = false;

        public OptionsForm(ConfigData p_Config)
        {
            InitializeComponent();
            ConfigOptions = p_Config;
        }

        private void FillLeagueListBox(LeagueData[] Leagues)
        {
            LeagueList.Items.AddRange(Leagues);
        }

        private void AddLeagueBtn_Click(object sender, EventArgs e)
        {
            AddOrEditLeagueForm leagueForm = new AddOrEditLeagueForm(new LeagueData());
            if (leagueForm.ShowDialog() == DialogResult.OK)
            {
                // get league from form and add the league to the list
                ConfigOptions.Leagues.Add(leagueForm.LeagueDetails);
                LeagueList.Items.Add(leagueForm.LeagueDetails.Name);
            }
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            Thread seperate = new Thread(new ThreadStart(SaveConfigFile));
            seperate.Start();
            this.DialogResult = DialogResult.OK;
        }

        public void SaveConfigFile()
        {
            ConfigFile.Save(ConfigOptions, "Config.xml");
        }

        private void OpenConfigFile()
        {
            using (FileStream file = new FileStream("Config.xml", FileMode.OpenOrCreate))
            {
                XmlSerializer serialize = new XmlSerializer(typeof(ConfigData));
                ConfigOptions = (ConfigData)serialize.Deserialize(file);
            }
        }

        private void RemoveLeagueBtn_Click(object sender, EventArgs e)
        {
            int selectedLeague = LeagueList.SelectedIndex;
            LeagueList.Items.RemoveAt(selectedLeague);
            ConfigOptions.Leagues.RemoveAt(selectedLeague);
        }
    }
}
